#include <time.h>
#include <d3dx9.h>
#include "Simon.h"
#include "Utils.h"

#define SIMON_SPEED 0.4f
#define GROUND_Y 100
#define BACKGROUND_FILE "image/BackgroundGame.png"

CSimon::CSimon(int _nCmdShow):CGame(_nCmdShow)
{
	simon = NULL;
	//all = NULL;
	camera = NULL;
}

CSimon::~CSimon()
{
	if(simon != NULL)
		delete simon;
	if(camera != NULL)
		delete camera;
}
void CSimon::LoadResources(LPDIRECT3DDEVICE9 d3ddv)
{
	srand((unsigned)time(NULL));

	D3DXCreateSprite(d3ddv,&G_SpriteHandler);

	Background = CreateSurfaceFromFile(d3ddv, BACKGROUND_FILE);

	HRESULT res = D3DXCreateSprite(d3ddv,&G_SpriteHandler);

	simon_x = 150;
	simon_y = 480;

	simon_vx = 0;
	simon_vx_last = 1.0f;
	simon_vy = 0;

	simon = new CSprite(new CTexture("image/simon.png", 8, 3, 24), 0, 3, 150);
	simon->SelectIndex(0);

	camera = new CCamera();
	background = new CLoadBackground();
	background->ImportFile("image/map.txt");
	background->AddResource();
}

void CSimon::RenderFrame(LPDIRECT3DDEVICE9 d3ddv, int deltaTime)
{	
	if(simon_x + simon_vx*deltaTime < background->_widthMap && simon_x + simon_vx*deltaTime > 0)
		simon_x += simon_vx * deltaTime;
	simon_y += simon_vy * deltaTime;

	// Simulate fall down
	if (simon_y > GROUND_Y) simon_vy -= 0.05f;
	else 
	{
		simon_y = GROUND_Y;
		simon_vy = 0;
	} 

	// Animate mario if she is running
	simon->Update(deltaTime);

	camera->UpdateCamera(simon_x);
	D3DXVECTOR2 marioInCamera = camera->Transform(simon_x, simon_y);


	// Background

	d3ddv->StretchRect(
		Background,			// from 
		NULL,				// which portion?
		G_BackBuffer,		// to 
		NULL,				// which portion?
		D3DTEXF_NONE);


	G_SpriteHandler->Begin(D3DXSPRITE_ALPHABLEND);

	background->DrawMap(camera);
	//All Object
	//all->Draw(camera);	
	if(simon_vx < 0 || simon_vx_last < 0)
		simon->Draw(marioInCamera.x, marioInCamera.y);
	else 
		simon->DrawFlipX(marioInCamera.x, marioInCamera.y);
	G_SpriteHandler->End();
}

void CSimon::ProcessInput(LPDIRECT3DDEVICE9 d3ddv, int t)
{
	if (IsKeyDown(DIK_RIGHT))
	{
		simon_vx = SIMON_SPEED;
		simon_vx_last = simon_vx;
	}	
	else 
		if (IsKeyDown(DIK_LEFT))
		{
			simon_vx = -SIMON_SPEED;
			simon_vx_last = simon_vx;
		}
		else 
		{
			simon_vx = 0;
			simon->Reset();
		}
}

void CSimon::OnKeyDown(int KeyCode)
{
	switch (KeyCode)
	{
	case DIK_SPACE:
		if (simon_y <= GROUND_Y) simon_vy += 0.75f;
		break;
	}
}